package com.sim.stream.util;

import com.sim.core.ImConst;
import com.sim.stream.ffch4j.CommandManager;
import com.sim.stream.ffch4j.CommandManagerImpl;
import com.sim.stream.ffch4j.commandbuidler.CommandBuidler;
import com.sim.stream.ffch4j.commandbuidler.CommandBuidlerFactory;
import com.sim.stream.ffch4j.data.CommandTasker;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ShellUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ShellUtil.class.getName());
    private static final CommandManager manager = new CommandManagerImpl();

    /**
     * 执行一个shell命令，并返回字符串值
     *
     * @param cmd
     * 命令名称&参数组成的数组（例如：{"/system/bin/cat", "/proc/version"}）
     * 命令执行路径（例如："system/bin/"）
     * @return 执行结果组成的字符串
     */
    public String exec(String[] cmd) {
        //调用示例：
//        ShellUtil.exec(new String[]{
//                "ffmpeg",
//                "-re",
//                "-i", "rtmp://192.168.10.44:1935/live/xs",
//                "-i", "rtmp://192.168.10.44:1935/live/szxx",
//                "-filter_complex", "amix=inputs=2:duration=first:dropout_transition=0",
//                "-acodec", "aac",
//                "-f", "flv",
//                "rtmp://192.168.10.44:1935/live/txh"
//        });
        LOG.info("start exec shell:{}",String.join(" ",cmd));
        StringBuffer result = new StringBuffer();
        try {
            ProcessBuilder builder = new ProcessBuilder(cmd);

            InputStream in = null;
            // 合并标准错误和标准输出
            builder.redirectErrorStream(true);
            // 启动一个新进程
            Process process = builder.start();

            // 读取进程标准输出流
            in = process.getInputStream();
            byte[] re = new byte[1024];
            while (in.read(re) != -1) {
                result = result.append(new String(re));
            }
            // 关闭输入流
            if (in != null) {
                in.close();
            }
        } catch (Exception ex) {
            LOG.error("exec shell exception,reason:{}",ex.toString());
        }
        LOG.info("exec result:{}",result.toString());
        return result.toString();
    }

    public Map<String,String> decodeRequestBody(String requestStr) throws UnsupportedEncodingException {
        Map<String,String> map = new HashMap<>();
        if(StringUtils.isNotBlank(requestStr)){
            requestStr = URLDecoder.decode(requestStr,"UTF-8");
            String[] entry = requestStr.split("&");
            for (String str:entry) {
                String[] kv = str.split("=");
                if(kv.length >= 2){
                    map.put(kv[0],URLDecoder.decode(kv[1],"utf-8"));
                }
                else{
                    map.put(kv[0],"");
                }
            }
        }
        return map;
    }

    /**
     * 更具rtmp回调的name获取group及user
     */
    public Pair<String,String> getGroupAndUser(String name){
        if(name.contains(ImConst.SUFFIX)){
            String[] tmp = name.split(ImConst.SUFFIX);
            return Pair.of(tmp[0],tmp[1]);
        }
        else{
            //没有group则为个人
            return Pair.of(name,name);
        }
    }

    /**
     * 执行ffmpeg命令
     * @param groupId
     * @param rtmpUrl
     * @throws Exception
     */
    public void ffmpegCommand(String groupId, List<String> users, String rtmpUrl) {
        CommandTasker tasker = manager.query(groupId);
        //如果当前任务存在，则停止任务
        if (tasker != null) {
            manager.stop(groupId);
        }
        if (users.size() > 0) {
            CommandBuidler commandBuidler = CommandBuidlerFactory.createBuidler()
                    .add("ffmpeg")
                    .add("-re");
            for (String user : users) {
                commandBuidler.add("-i", rtmpUrl + "/" + groupId + ImConst.SUFFIX + user);
            }
            commandBuidler.add("-filter_complex", String.format("amix=inputs=%d:duration=first:dropout_transition=10", users.size()));
            commandBuidler.add("-acodec", "aac");
            commandBuidler.add("-f", "flv");
            commandBuidler.add(rtmpUrl + "/" + groupId);
            manager.start(groupId, commandBuidler.get());

        }
    }

}
